// FUI-File 文件管理器 3.0

function get(name){name=name.replace(/[]/,"\[").replace(/[]/,"\[").replace(/[]/,"\\\]");var regexS="[\\?&]"+name+"=([^&#]*)";var regex=new RegExp(regexS);var results=regex.exec(window.self.location.href);if(results==null)return"";else{return results[1]}};

var ac=get('tid');

//读取目录

function folder() {
    // 清空两个元素的内容
    $('#folder').empty();
    $('#file').empty();

    $.post('api/?l=list', {}, function (data) {
        // 创建树形结构
        const $rootUl = createTree(data.folder);
        // 将生成的树形结构添加到指定元素中
        $('#folder').append($rootUl);
        // 检查本地存储中是否有上次点击的文件夹路径
        let ls = localStorage.getItem('lsid');
        if (ls) {
            $('#'+ls).click();
        }else{
			 $('#g1').click();
		}
		
    }, 'json');

    function createTree(data, $parentUl = null, parentPath = '') {
        const rootUl = $parentUl || $('<ul>');
        
        for (const key in data) {
            if (data.hasOwnProperty(key)) {
                const currentPath = parentPath? `${parentPath}/${key}` : key;
                const $li = $('<li>');
                const $a = $('<a href="javascript:;" id="f' + key + '" data-url="' + currentPath + '">')
                   .text(key)
                   .attr('data-url', currentPath);

                $li.append($a);

                const $subUl = $('<ul>');
                if (typeof data[key] === 'object') {
                    createTree(data[key], $subUl, currentPath);
                }
                $li.append($subUl);
                rootUl.append($li);
            }
        }

        return rootUl;
    }
}

folder();



//打开目录
$(document).on("click", ".folder a", function () {
	$('#file').empty();
    $('.folder a').removeClass('on');
    $(this).addClass('on');
    $(this).next('ul').toggle();
	dir=$(this).data('url');
    localStorage.setItem('lsid', $(this).attr('id'));    // 记忆上次打开的
	files(dir)
	$('#tag').html(''+dir+'/')
	
});

	
//读取文件	
 function files(dir){ 
      $('#file').empty();
	  i=0;
      $.post('api/?l=file', {  
         dir:dir
      }, function (data) {
			$.each(data, function (index, data) {
				  i++;
				  var extension = data.name.split('.').pop().toLowerCase();
				  
				  var sizeInKB=(data.size / 1024).toFixed(2)
				      if (sizeInKB > 1024) {
						 size= (sizeInKB / 1024).toFixed(2) + " MB"; 
					  }else{
						 size= sizeInKB +" KB";
					  }
				 
				  var $li = $('<li>');
					 
					  if (['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'bmp'].includes(extension)) {
						 ico= '<img src="ico/'+ extension + '.svg" data-src="'+data.folder+'/' + data.name + '"/>';
						 cla='ico';
					  } else {
						 ico='<img src="ico/'+ extension + '.svg"/>'; 
						 cla='';
					  }
					  
					  $li.append('<a href="javascript:;" id="w'+i+'" class="'+cla+'" data-url="'+data.folder+'/' + data.name + '" data-kzm="'+ extension +'" data-size="'+data.size+'" title="占用空间 '+size+'\n上传时间 '+data.accessTime+'">'+ico+'<b>'+data.name+'</b><s>时间:'+data.accessTime+' </s><s>大小:'+size+' </s></a>');
					  
				  $('#file').append($li);
			});
		  
		   loadVisibleImages();// 首次加载时加载当前屏幕可见的图片
		   layer.photos({ photos: '.ico' }); 
      },'json');
   }


//延迟加载图

    function loadVisibleImages() {
      $('.file img').each(function () {
        var img = $(this);
        var rect = img[0].getBoundingClientRect();
        var fileRect = $('.file')[0].getBoundingClientRect();
        if (rect.top >= 0 && rect.bottom <= fileRect.height + 100) {
          img.attr('src', img.attr('data-src'));
        }
      });
    }
    // 当.file 元素滚动时加载图片
    $('.file').on('scroll', function () {
      if ($('.file').data('scrollTimer')) {
        clearTimeout($('.file').data('scrollTimer'));
      }
      $('.file').data('scrollTimer', setTimeout(() => {
        loadVisibleImages();
      }, 200));
    });


//空白处点击复位

//单击选中文件
$(document).on("click","#file li",function(e){
			  e.preventDefault();
			  $(this).toggleClass('on');
			  edit();
})

//双击打开文件
$(document).on("dblclick","#file li",function(e){
			  e.preventDefault();
	         
			  id=$(this).find("a").attr('id');
			  src=$(this).find('a > img').attr('src');
			  wjm=$(this).find("b").text();
			  kzm=$(this).find("a").data('kzm');	
			  url=$(this).find("a").data('url');
			  $('#file li').removeClass('on');
			  $(this).addClass('on');
			  if(ac=='edit'){ edit(); }
			  
//为选择状态时  
if(ac != 0 ){
		  index=parent.layer.getFrameIndex(window.name);
		 
          if(ac=='edit1'){
			  //富文本tinymce-组件上传	
				var editor=parent.tinymce.activeEditor;
					parent.$("[role='combobox']").val(url);
					parent.layer.close(index);
					parent.layer.msg('添加成功！',{icon: 1,time: 1000}, function(){});
		 
		  }else if(ac=='ups'){
			  
			  //批量上传	
					parent.$('.ups').append('<a><i></i><img src="'+url+'"/></a>');
					parent.layer.close(index);  
					
		  }else{
		      //如果为选择模式
					parent.$('#'+ac+' i').text(url);
					parent.$('#'+ac+' input').val(url);
					parent.$('#'+ac+' img').attr('src',url);
					parent.$('#'+ac+'').attr('src',url);
					parent.layer.close(index);  
		  }
	  
 }else{
	
	  //为预览状态
		  function openFile(src, wjm, kzm, url) {
				if (['jpg', 'jpeg', 'gif', 'png', 'bmp', 'tiff', 'svg'].includes(kzm)) {
					
					
					
				} else if (['xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx'].includes(kzm)) {
					event.preventDefault();
					layer.open({
						type: 2,
						title: [wjm],
						skin: 'layui-layer-win10',
						area: ['80%', '94%'],
						maxmin: true,
						shadeClose: true,
						content: [`https://view.officeapps.live.com/op/embed.aspx?src=${window.location.hostname}/${url}`],
						zIndex: layer.zIndex,
						success: function (layero) {
							layer.setTop(layero);
						},
						end: function () { }
					});
				} else if (['html', 'htm', 'php', 'asp', 'js', 'css', 'txt', 'csv', 'pdf', 'swf', 'mp3', 'mp4'].includes(kzm)) {
					event.preventDefault();
					layer.open({
						type: 2,
						title: [wjm],
						skin: 'layui-layer-win10',
						area: ['80%', '94%'],
						maxmin: true,
						shade: [0.8, '#fff'],
						shadeClose: true,
						content: [url],
						zIndex: layer.zIndex,
						success: function (layero) {
							layer.setTop(layero);
						},
						end: function () { }
					});
				} else {
					alert('不支持预览此格式');
				}
			}
			
			openFile(src, wjm, kzm, url);

	}
	
	});	


//右键菜单碰壁触发事件
function setMenuPosition(menuElement, event) {
			const pageY = event.pageY;
			const pageX = event.pageX;
			const docHeight = $(document).height();
			const docWidth = $(document).width();
		
			const topValue = pageY + 175 > docHeight? pageY - 175 : pageY;
			const leftValue = pageX + 150 > docWidth? pageX - 150 : pageX;
		
			menuElement.style.top = topValue + "px";
			menuElement.style.left = leftValue + "px";
}

//全局右键菜单
$(document).on("contextmenu","html",function(e){
			  e.preventDefault()// 阻止右键菜单默认行为
			  xurl=$('.folder .on').data('url');
			  CB=$('#CB').val();
			  $("#m1").show();
			  setMenuPosition(m1, e);
})


//目录右键菜单
$(document).on("contextmenu",".folder a",function(e){
			  e.preventDefault() // 阻止右键菜单默认行为
			  id=$(this).attr('id');
			  url=$(this).data('url');
			 
			  $('.folder a').removeClass('on');
			  $(this).addClass('on');
			  $(this).next('ul').toggle();
			  $("#m3").show();
			   
			  setMenuPosition(m3, e);
})
	
//文件右键菜单
$(document).on("contextmenu",".file li",function(e){
			  e.preventDefault() // 阻止右键菜单默认行为
			  
			  $(this).addClass('on');
			   id=$(this).find("a").attr('id');
			  src=$(this).find('a > img').attr('src');
			  wjm=$(this).find("b").text();
			  kzm=$(this).find("a").data('kzm');	
			  url=$(this).find("a").data('url');
			 
			  $("#m2").show();
			  setMenuPosition(m2, e);
})


//关闭右键
  document.addEventListener("click", function(event){$(".myMenu").hide();});
		

		
//新窗口打开
	$(document).on("click","#open",function(){
		  window.open(url);
	});	

//下载

	$(document).on("click","#down",function(){
		var link = $('<a>', { href: url, download: wjm });
        $('body').append(link);
        link[0].click();
        link.remove();
	});	
	
//目录打开	
	$(document).on("click","#f_open",function(){
		   
	      $("#"+id+"").click();
	});	
		
//属性 ok	
	$(document).on("click","#attr",function(){
		
	     $.post('api/?l=attr', {  
             url:url
         }, function (data) {
			 
			kb=(data.size / 1024).toFixed(2)
			layer.open({
			  type: 1,
			  title: false,
			  closeBtn: 0,
			  shadeClose: true,
			  skin: 'attrg',
			  content: '<img src="'+src+'"/><div><p>文件路径:<a href="'+url+'" download="">'+window.location.host+url.replace(/\.\.\//g,'/')+'</a></p><p>占用空间:'+kb+' KB</p><p>访问时间:'+data.atime+'</p><p>修改时间:'+data.mtime+'</p></div>'
			});
			
	   },'json')
	});	

//文件夹属性	
	$(document).on("click","#f_attr,#q_attr",function(){
	     $.post('api/?l=f_attr', {  
              url:xurl
         }, function (data) {
			 kb=(data.size / 1024).toFixed(2)
			layer.open({
			  type: 1,
			  title: false,
			  closeBtn: 0,
			  shadeClose: true,
			  skin: 'attrg',
			  content: '<img src="ico/dir.svg"/><div><p>目录路径:'+xurl+' </p><p>目录权限:'+data.info+' </p><p>占用空间:'+kb+' KB</p><p>访问时间:'+data.atime+'</p><p>修改时间:'+data.mtime+'</p></div>'
			});
			
	   },'json')
	});	
				   

//文件右键命令
   $(document).on("click","#edit",function(){
	  event.preventDefault();
		
		   if(kzm =='htm' || kzm=='html' || kzm=='css' || kzm=='js' || kzm=='txt' ){
					layer.open({
					type: 2,
					title:['编辑 '+xurl+''+wjm],
					area: ['96%','94%'],
					shade:[0.8, '#fff'],
					maxmin: false,//显示最大化最小化按钮
					content: ['dm.php?u='+xurl+'/'+wjm+''],//自动从href里获取url
					zIndex: layer.zIndex, success: function(layero){layer.setTop(layero);
					},end: function(){   //关闭后执行
							//location.reload();//刷新
						}
				});

			}else{
					layer.msg('此文件不支持编辑');
				}
	
	});	
	

//查看方式
	  $(document).on("click","#ktb",function(){
		  layer.msg('图标显示');
	      $(".file").removeClass("lb");
	   });	
	  $(document).on("click","#klb",function(){
		  layer.msg('列表显示');
	      $(".file").addClass("lb");
	   });

  
 //删除文件 ok
	$(document).on("click","#del",function(){
		 
		         dir=$('.folder .on').data('url'); 
			     const fileNames = [];
				 i=0;
				 $('#file .on').each(function () {
					i++; 
					const fileName = $(this).find('b').text();
					fileNames.push(fileName);
				  });
		
		 
		layer.msg('你确定要删除选中的文件吗？<br>共'+i+'个文件', {time: 0 ,shade:[0.8, '#fff'],icon: 3 ,btn: ['确定', '取消'],
			 yes: function(index){
			    
			   $.post('api/?l=dels', {  
				    url:dir,
					fileNames:fileNames
				 }, function (data) {
					 
					layer.msg(data);
					files(dir)
					layer.close(index);	
						
				 },'json')
				 
			}
		});
	});		

//删除文件夹	
$(document).on("click","#rd",function(){
		
		layer.msg('你确定要删除 '+url+' 吗？', {time: 0 ,shade:[0.8, '#fff'],icon: 3 ,btn: ['确定', '取消'],
			 yes: function(index){
			  $.post('api/?l=rd', {  
				 url:url
				 }, function (data) {
					layer.msg(data);
					layer.close(index);	
					localStorage.setItem('lsid', 'g1'); 
					folder()
				 },'json')
				 
			}
		});
	});	

//重命名文件夹	
$(document).on("click","#ren",function(){
	     
		layer.prompt({title: ['请输入的新文件夹名称'],value: ''},function(val, index){
              
			 $.post('api/?l=ren', {  
				 oldName:url,
				 newName:val
			 }, function (data) {
				layer.msg(data);
				layer.close(index);	 
				dir=$('.folder .on').data('url');
			    folder()
			 },'json')
			  
			}); 
});
	
//重命名文件ok	
$(document).on("click","#rename",function(){
		layer.prompt({title: ['请输入'+wjm+'的新名称'],value: ''},function(val, index){
             
			 $.post('api/?l=rename', {  
				 oldName:url,
				 newName:val
			 }, function (data) {
				layer.msg(data);
				layer.close(index);	 
				dir=$('.folder .on').data('url');
			    files(dir)
			 },'json')
			  
			}); 
});
	
//刷新ok		   
		$(document).on("click","#shua,#f_shua",function(){
		    layer.msg('已刷新');
		    dir=$('.folder .on').data('url');
			files(dir)
		});	

//复制ok
	
  	$(document).on("click","#copy",function(){
		layer.msg('已复制,请在合适位置粘贴');
		   
			     const fileNames = [];
				 i=0;
				 $('#file .on').each(function () {
					i++; 
					const fileName = $(this).find('a').data('url');
					fileNames.push(fileName);
				  });
				  
		   $('#CB').val(fileNames);
		   $('#paste').show();
	});	
	
	   
//粘贴ok
	$(document).on("click","#paste",function(){
		
		   $.post('api/?l=copys', {  
				 yurl:CB,
				 xurl:xurl
			 }, function (data) {
				layer.msg(data);
				dir=$('.folder .on').data('url');
			    files(dir)
			 },'json')

	});

//新建文件夹	
$(document).on("click","#md,#md1",function(){
		 
		 dir=$('.folder .on').data('url');
		 layer.prompt({title: ['请输入文件夹名称'],value: ''},function(val, index){
				  
				 $.post('api/?l=md', {  
					 dir:dir,
					 name:val
				 }, function (data) {
					layer.msg(data);
					layer.close(index);	 
					folder()
				 },'json')
			 
		       });
	});	


//批量上传	
layui.use(['layer','element','flow','upload'], function(){
	  var layer = layui.layer
	  ,flow = layui.flow
	  ,upload = layui.upload
	  ,element = layui.element;
 		
	  flow.lazyimg({elem: '.file img',scrollElem: '#file'}); 
		
  //文件上传

		var upload = layui.upload;
		nmsg='';
        upload.render({
            elem: '.up',
            accept: 'file',
            multiple: 'true',
            url: 'api/?l=up',
            data: {ml: function(){ return $('.folder .on').data('url')} },
            before: function () {
                layer.load('上传中..', { icon: 16, shade: 0.01 });
            },
            done: function (res) {
                nmsg+='<p>'+res.msg+'</p>';
            },
			allDone: function(obj){ //当文件全部被提交后，才触发
						layer.closeAll('loading');
						layer.msg(nmsg);
						files(function(){ return $('.folder .on').data('url') })
						nmsg='';
					  },
            error: function () {
                layer.msg('上传失败了');
            }
        });	
				
				
				
});

$('.upimg').on('click', function (event) {
        event.preventDefault();
		dir=$('.folder .on').data('url');
		
		layer.open({
			type: 2,
			title:false,
			closeBtn: 0,
			anim: 'slideLeft', 
			offset: 'r',
			area: ['700px','100%'],
			shade:[0.8, '#fff'],
			shadeClose: true,
			maxmin: false,
			content: ['img.html?u='+dir],//自动从href里获取url
			zIndex: layer.zIndex, success: function(layero){layer.setTop(layero);
			},end: function(){ 
				files(dir)
			}
	    });
	});

//框选功能
    let startX, startY;
    let isDrawing = false;
$(".file").mousedown(function (e) {
		e.preventDefault();
      startX = e.pageX;
      startY = e.pageY;
      isDrawing = true;
      $('body').append('<div class="selection"></div>');
      $('.selection').css({
        left: startX,
        top: startY,
        width: 0,
        height: 0
      });
});

$(".file").mousemove(function (e) {
		e.preventDefault();
      if (isDrawing) {
        const currentX = e.pageX;
        const currentY = e.pageY;
        const width = Math.abs(currentX - startX);
        const height = Math.abs(currentY - startY);
        const left = startX < currentX? startX : currentX;
        const top = startY < currentY? startY : currentY;
        $('.selection').css({
          left: left,
          top: top,
          width: width,
          height: height
        });

         
        $('#file li').each(function () {
          const $li = $(this);
          const liOffset = $li.offset();
          const liWidth = $li.outerWidth();
          const liHeight = $li.outerHeight();
        
		  if (left < liOffset.left + liWidth && left + width > liOffset.left && top < liOffset.top + liHeight && top + height > liOffset.top) {
              $li.addClass('on');
          } else {
          
		      $li.removeClass('on');
          }
        });
      }
    });
  
  //框选松开鼠标时
    $(document).mouseup(function () {
      isDrawing = false;
      $('.selection').remove();
       //$('li').removeClass('on');
	   if(ac=='edit'){ edit() }
	  
    });		
	

//富文本调用	
 function edit(){ 
			        var arrList = []; //给富文本预留的数组, 必须放到外面
					$('#file .on').find('img').each(function () {
						arrList.push("<img src='" + $(this).attr('src') + "'/>");
					});
					
					if(ac=='edit'){
						var editor = parent.tinymce.activeEditor;
						var up = parent.up;
						up.res = arrList.join('');
					}
 }